package com.shengdou.as.slopsapptest.Fragment;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.shengdou.as.slopsapptest.Activity.AboutMineActivity;
import com.shengdou.as.slopsapptest.Activity.ContactUsActivity;
import com.shengdou.as.slopsapptest.Activity.FailureListActivity;
import com.shengdou.as.slopsapptest.Activity.LoginActivity;
import com.shengdou.as.slopsapptest.Activity.MainActivity;
import com.shengdou.as.slopsapptest.Activity.ManagerAddActivity;
import com.shengdou.as.slopsapptest.R;
import com.shengdou.as.slopsapptest.actionsheet_dialogview.NewActionSheetDialog;
import com.shengdou.as.slopsapptest.actionsheet_dialogview.OnOperItemClickL;
import com.shengdou.as.slopsapptest.base.BaseFragment;
import com.shengdou.as.slopsapptest.bean.person;
import com.shengdou.as.slopsapptest.utils.BitmapUtil;
import com.shengdou.as.slopsapptest.utils.CameraUtil;
import com.shengdou.as.slopsapptest.utils.Constants;
import com.shengdou.as.slopsapptest.utils.DataCleanManager;
import com.shengdou.as.slopsapptest.utils.FileUtils;
import com.shengdou.as.slopsapptest.utils.HttpUtils;
import com.shengdou.as.slopsapptest.utils.LogUtil;
import com.shengdou.as.slopsapptest.utils.NetConstant;
import com.shengdou.as.slopsapptest.utils.SharedPreferenceUtil;
import com.shengdou.as.slopsapptest.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class MyFragment extends BaseFragment {
    private person persons;
    private TextView mTxtExit;//退出登录
    private TextView mTxtversion;//版本号
    private int level;//判断是否为管理员
    private LinearLayout mLinearManager, mLinearAbout;
    private LinearLayout mLinearHint;
    private LinearLayout mLinearCall;
    private LinearLayout mLinearVersion;
    private String[] stringItemsPic = {"拍照", "从相册选择"};
    private ImageView mImg, mImgDefault;//头像
    private TextView mTxtName;//用户名
    public static final int SELECT_PIC_REQUEST_CODE = 1;// 从相册中选择图片
    public static final int TAKE_PIC_REQUEST_CODE = 2;// 使用相机拍照
    public static final int PHOTO_REQUEST_CUT = 3;// 使用相机拍照
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 4;//调用读取权限
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 5;//调用写入权限
    private boolean select;//判断是否开启权限
    String status = "";//新版本路径
    private File photo;// 头像的照片文件
    private Uri photoUri;
    private static final String IMGPATH = FileUtils.IMAGES_PATH;//路径
    private static final String IMAGE_NAME = FileUtils.createImageFileName();//名字
    private Map<String, String> params = new HashMap<>();
    private LinearLayout mRelaCancel;//清除缓存
    private TextView mCancel;
    private String versionName;//版本信息
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.USERINFO:
                    //获取用户信息
                    String userInfo = msg.obj.toString();
                    LogUtil.e("userInfo", userInfo);
                    SharedPreferenceUtil.savePreferenceString(getActivity(), "mobile", null);
                    persons = new Gson().fromJson(userInfo, person.class);
                    SharedPreferenceUtil.savePreferenceString(getActivity(), "portrait", NetConstant.SERVICES() + persons.getPortrait());
                    if (persons.getPortrait() != null || !persons.getPortrait().equals("")) {
                        mImg.setVisibility(View.VISIBLE);
                        mImgDefault.setVisibility(View.GONE);
                        new DownSmallPic(mImg).execute(SharedPreferenceUtil.getPreferenceString(getActivity(), "portrait"));// 显示头像
//            Glide.with(getActivity()).load(getFactory()).into(mImg);
                    } else {
                        mImg.setVisibility(View.GONE);
                        mImgDefault.setVisibility(View.VISIBLE);
                    }
                    break;
                case Constants.LOGINOUT:
                    //退出登录
                    String result = msg.obj.toString();
                    LogUtil.e("result", result);
                    SharedPreferenceUtil.savePreferenceString(getActivity(), "mobile", null);
                    SharedPreferenceUtil.savePreferenceString(getActivity(), "session_id", null);
                    FileUtils.saveObject(getActivity(), "PoolDataBeans", null);
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    JPushInterface.deleteAlias(getActivity(), 0);
                    getActivity().finish();
                    MainActivity.exit();
                    break;
                case Constants.PICTUREUPLOAD:
                    mImg.setVisibility(View.VISIBLE);
                    mImgDefault.setVisibility(View.GONE);
                    //图片加载

                    Bitmap bitmap = (Bitmap) msg.obj;
                    if (bitmap != null) {
                        Bitmap bitmaps = BitmapUtil.returnBitMap(bitmap);
                        mImg.setImageBitmap(bitmaps);
                    }
                    break;
                case Constants.VERSION:
                    //获取版本信息
                    String data = msg.obj.toString();
                    LogUtil.e("获取版本信息", data);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(data);
                        status = jsonObject.getJSONObject("data").getString("download");
                        String version = jsonObject.getJSONObject("data").getString("version");
                        LogUtil.e("获取版本路径", status);
                        if (Float.parseFloat(version) > Float.parseFloat(versionName)) {
                            requestWritePermission();
                        } else {
                            ToastUtils.showToast("已经是最新版本了！");
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    };

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_my, null);
    }

    @Override
    protected void initFindViewById(View view) {
        String name = SharedPreferenceUtil.getPreferenceString(getActivity(), "real_name");
        String phone = SharedPreferenceUtil.getPreferenceString(getActivity(), "mobile");
        String mImageHead = SharedPreferenceUtil.getPreferenceString(getActivity(), "portrait");
        level = SharedPreferenceUtil.getPreferenceInt(getActivity(), "level");
        mTxtExit = (TextView) view.findViewById(R.id.txt_exit);
        mTxtExit.setOnClickListener(this);
        mImg = (ImageView) view.findViewById(R.id.img_head);
        mImgDefault = (ImageView) view.findViewById(R.id.default_head);
        mTxtName = (TextView) view.findViewById(R.id.txt_phone);
        if (name == null || name.equals("")) {
            mTxtName.setText(phone);
        } else {
            mTxtName.setText(name);
        }
        if (mImageHead != null || !mImageHead.equals("")) {
            mImg.setVisibility(View.VISIBLE);
            mImgDefault.setVisibility(View.GONE);
            new DownSmallPic(mImg).execute(SharedPreferenceUtil.getPreferenceString(getActivity(), "portrait"));// 显示头像
//            Glide.with(getActivity()).load(getFactory()).into(mImg);
        } else {
            mImg.setVisibility(View.GONE);
            mImgDefault.setVisibility(View.VISIBLE);
        }
        mImgDefault.setOnClickListener(this);
        mImg.setOnClickListener(this);
        mLinearManager = (LinearLayout) view.findViewById(R.id.linear_managerlist);
        mLinearManager.setOnClickListener(this);
        mLinearHint = (LinearLayout) view.findViewById(R.id.linear_hitchlist);
        mLinearHint.setOnClickListener(this);
        mLinearCall = (LinearLayout) view.findViewById(R.id.linear_callmine);
        mLinearCall.setOnClickListener(this);
        mLinearAbout = (LinearLayout) view.findViewById(R.id.linear_aboutmine);
        mLinearAbout.setOnClickListener(this);
        mRelaCancel = (LinearLayout) view.findViewById(R.id.relative_cancel);
        mRelaCancel.setOnClickListener(this);
        mLinearVersion = (LinearLayout) view.findViewById(R.id.linear_version);
        mLinearVersion.setOnClickListener(this);
        //版本信息
        mTxtversion = (TextView) view.findViewById(R.id.txt_version_code);
        versionName = SharedPreferenceUtil.getPreferenceString(getActivity(), "versionName");
        mTxtversion.setText("V" + versionName);
        if (level == 0) {
            mLinearManager.setVisibility(View.GONE);
        } else {
            mLinearManager.setVisibility(View.VISIBLE);
        }
        mCancel = (TextView) view.findViewById(R.id.txt_cache);


    }

    @Override
    public void initData() {
        //获取用户信息
//        HttpUtils.post(mHandler, NetConstant.USERINFO, params, Constants.USERINFO, getActivity());

        try {
            //添加缓存数据
            String Total = DataCleanManager.getTotalCacheSize(getActivity());
            mCancel.setText(Total);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.default_head:
                //头像选择
                requestCameraPermission();
                break;
            case R.id.img_head:
                //头像选择
                requestCameraPermission();
                break;
            case R.id.txt_exit:
                //退出登录
                HttpUtils.post(mHandler, NetConstant.LOGINOUT(), params, Constants.LOGINOUT, getActivity());
                break;
            case R.id.linear_managerlist:
                //管理列表
                startActivity(new Intent(getActivity(), ManagerAddActivity.class));
                break;
            case R.id.linear_hitchlist:
                //故障列表
                startActivity(new Intent(getActivity(), FailureListActivity.class));
                break;
            case R.id.linear_callmine:
                //联系我们
                startActivity(new Intent(getActivity(), ContactUsActivity.class));
                break;
            case R.id.linear_aboutmine:
                //关于我们
                startActivity(new Intent(getActivity(), AboutMineActivity.class));
                break;
            case R.id.linear_version:
                //版本更新
                checkUploadData();
                break;
            case R.id.relative_cancel:
                //清除缓存
                if (mCancel.getText().toString().equals("0K")) {
                    ToastUtils.showToast("没有缓存数据！");
                    return;
                } else {
                    final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                    alertDialog.show();
                    alertDialog.getWindow().setContentView(R.layout.dialog_delect_data);
                    alertDialog.getWindow().findViewById(R.id.dialog_verify_cancle).setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            alertDialog.cancel();
                        }
                    });
                    alertDialog.getWindow().findViewById(R.id.dialog_verify_go).setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            DataCleanManager.clearAllCache(getActivity());
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
//                                    SystemClock.sleep(3000);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            mCancel.setText("0K");

                                        }
                                    });
                                }
                            }).start();
                            alertDialog.cancel();
                        }
                    });

                }
                break;
        }
    }

    int versionCurrent;

    // 检查版本更新
    private void checkUploadData() {

        PackageManager manager = getActivity().getPackageManager();
        PackageInfo info;
        try {
            info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            versionCurrent = info.versionCode;
            LogUtil.e("versionCurrent", versionCurrent + "");
            params.put("client", "Android");
            params.put("version", info.versionName);
            HttpUtils.postFactory(mHandler, NetConstant.VERSION, params, Constants.VERSION, getActivity());
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //版本更新
    private void showUpdateDialog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
        alertDialog.show();
        alertDialog.getWindow().setContentView(R.layout.alert_dialog_base);
        alertDialog.getWindow().findViewById(R.id.dialog_verify_cancle).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.cancel();
            }
        });
        alertDialog.getWindow().findViewById(R.id.dialog_verify_go).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!status.equals("")) {
                    if (select == true) {
                        HttpUtils.inProgress(getActivity(), status, Environment.getExternalStorageDirectory().getAbsolutePath());
                    } else {
//                        HttpUtils.inProgress(getActivity(), status, getActivity().getFilesDir().getAbsolutePath());
//                        ToastUtils.showToast("sd卡权限未开！不能更新版本");
                        Uri uri = Uri.parse(status);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        startActivity(intent);
                    }
                }
                alertDialog.cancel();
            }
        });
    }

    //设置写入权限
    private void requestWritePermission() {
        int hasWriteContactsPermission = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteContactsPermission
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
            return;
        } else {
            select = FileUtils.avaiableMedia();//判断是否开启权限
            showUpdateDialog();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case READ_EXTERNAL_STORAGE_REQUEST_CODE:
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        showChoosePicDialog();
                    } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {

                        if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                                Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            ToastUtils.showToast("您已禁止询问sd卡权限...");
                        } else {
                            ToastUtils.showToast("没有设置权限");
                        }
                    }

                }
                break;
            case WRITE_EXTERNAL_STORAGE_REQUEST_CODE:
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        select = FileUtils.avaiableMedia();//判断是否开启权限
                        showUpdateDialog();//下载
                    } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        select = false;
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            ToastUtils.showToast("您已禁止询问sd卡权限...");
                        } else {
//                            ToastUtils.showToast("没有设置权限");
                        }
                    }
                }
                break;
            default: {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    //设置读取权限
    private void requestCameraPermission() {
        int hasWriteContactsPermission = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
        if (hasWriteContactsPermission
                != PackageManager.PERMISSION_GRANTED) {

            showMessageOKCancel("你需要设置请求读取sd卡权限",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(getActivity(),
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_REQUEST_CODE);
                        }
                    });
            return;

        } else {
            showChoosePicDialog();
        }
    }

    /**
     * 选择头像
     */
    private void showChoosePicDialog() {

        File file = new File(IMGPATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        photo = new File(file, IMAGE_NAME);
        photoUri = Uri.fromFile(photo);
        /**
         * 带动画的选择框
         */
        final NewActionSheetDialog dialogPic = new NewActionSheetDialog(getContext(), stringItemsPic, null);
        dialogPic.isTitleShow(false).show();

        dialogPic.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        ShowCameraAction(TAKE_PIC_REQUEST_CODE);
                        dialogPic.dismiss();
                        break;
                    case 1:
                        choseHeadImageFromGallery(SELECT_PIC_REQUEST_CODE);
                        dialogPic.dismiss();

                        break;
                }

            }
        });
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(getActivity())
                .setMessage(message)
                .setPositiveButton("确定", okListener)
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

    // 从本地相册选取图片作为头像
    private void choseHeadImageFromGallery(int selectPicRequestCode) {

        Intent intentFromGallery = new Intent();
        if (Build.VERSION.SDK_INT < 19) {
            intentFromGallery = new Intent(Intent.ACTION_GET_CONTENT);
            intentFromGallery.setType("image/*");
        } else {
            intentFromGallery = new Intent(
                    Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intentFromGallery, selectPicRequestCode);
    }

    private void ShowCameraAction(int i) {
        //到系统照相机
        Intent intentFromCapture = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        if (CameraUtil.hasSdcard()) {
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,
                    photoUri);
        }
        startActivityForResult(intentFromCapture, i);
    }

    // 设置显示拍到的照片
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            // 如果没有拍照或者没有选择照片，点击返回 就直接returned 防止空指针 和报错
            return;
        }
        if (requestCode == SELECT_PIC_REQUEST_CODE) {
            // 从相册中选择图片
            cropRawPhoto(data.getData());
        } else if (requestCode == TAKE_PIC_REQUEST_CODE) {
            // 使用相机拍照
            if (CameraUtil.hasSdcard()) {
                File tempFile = new File(
                        Environment.getExternalStorageDirectory(),
                        IMAGE_NAME);
                cropRawPhoto(photoUri);
            } else {
                ToastUtils.showToast("头像设置失败");
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            if (photoUri != null) {
                // 从剪切图片返回的数据
//                ToastUtils.showToast(Uri.fromFile(photo).getPath() + "---------");
                File file = new File(photoUri.getPath());
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //进入到这里代表没有权限.
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, SELECT_PIC_REQUEST_CODE);
                    if (file.exists()) {
                        lunban(file);
                    } else {
                        file.mkdirs();
                    }
                } else {
                    if (file.exists()) {
                        lunban(file);
                    } else {
                        file.mkdirs();
                    }
                }
            }
        }
    }

    private void lunban(File bitmap) {
        Luban.get(getActivity())
                .load(bitmap)                     //传人要压缩的图片
                .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
                .setCompressListener(new OnCompressListener() { //设置回调

                    @Override
                    public void onStart() {
                        //TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        //TODO 压缩成功后调用，返回压缩后的图片文件
                        LogUtil.e("file", file + "");
                        updateHead(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        //TODO 当压缩过去出现问题时调用
                        LogUtil.e("filesssss", e + "");
                    }
                }).launch();    //启动压缩
    }


    /**
     * 裁剪图片
     */
    public void cropRawPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/jpeg");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 312);
        intent.putExtra("outputY", 312);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                photoUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("scaleUpIfNeeded", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    //上传头像
    private void updateHead(File file) {

        OkHttpUtils.post(NetConstant.PICTUREUPLOAD())//
                .params("pirtraut", file, IMAGE_NAME)//
                .url(NetConstant.PICTUREUPLOAD())
                .params("session_id", SharedPreferenceUtil.getPreferenceString(getActivity(), "session_id"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LogUtil.e("resultHeadImg", s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            int status = jsonObject.getInt("status");
                            if (status == 0) {
                                ToastUtils.showToast(jsonObject.getString("status_text"));
                            } else if (status == 100) {
                                ToastUtils.showToast(jsonObject.getString("text"));
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                getActivity().startActivity(intent);
                            } else {
                                ToastUtils.showToast(jsonObject.getString("status_text"));
                                String img = jsonObject.getString("img_url");
                                SharedPreferenceUtil.savePreferenceString(getActivity(), "portrait", img);
                                HttpUtils.mImageView(mHandler, img, Constants.PICTUREUPLOAD);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                });
    }

    //获取头像
    public String getFactory() {
        String ImageLoad;
        Object obj = FileUtils.getObject(getActivity(), "person");
        person person = null;
        if (obj instanceof person) {
            person = (person) obj;
        }
        if (person != null) {
            ImageLoad = person.getPortrait();
            return ImageLoad;
        } else {
            return "";
        }

    }
    // 转头像

    public class DownSmallPic extends AsyncTask<String, Integer, Bitmap> {
        private ImageView iv;

        public DownSmallPic(ImageView iv) {
            this.iv = iv;
            LogUtil.e(iv + "第二次得到");
        }

        @Override
        protected Bitmap doInBackground(String... params) {

            String url = params[0];
            Bitmap bitmap = null;
            try {
                //加载一个网络图片
                InputStream is = new URL(url).openStream();
                bitmap = BitmapUtil.returnBitMap(BitmapFactory.decodeStream(is));
                return bitmap;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;

        }

        protected void onPostExecute(Bitmap result) {
            LogUtil.e(result + "------得到结果");
            if (result == null) {
                mImg.setVisibility(View.GONE);
                mImgDefault.setVisibility(View.VISIBLE);
            } else {
                iv.setImageBitmap(result);
            }
        }
    }

}
